<template>
    <div>
        <el-breadcrumb separator-class="el-icon-arrow-right" class="el-bread-group">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>权限管理</el-breadcrumb-item>
            <el-breadcrumb-item>角色列表</el-breadcrumb-item>
        </el-breadcrumb>
        <el-card class="card">
            <div class="btn-add">
                <el-button type="primary" @click="clickAddRole">新增角色</el-button>
            </div>
            <el-table
            :data="rolesData"
            stripe
            border
            style="width: 100%">
            <el-table-column type="expand">
            <template slot-scope="props">
              <el-row :gutter="20"
                :key="item.id"
                v-for="(item,i) in props.row.children"
                :class="['botbd' , i === 0 ? 'topbd' : '']"
                class="vmiddle"
                >
                <el-col :span="5" >
                  <el-tag closable @close="removeRights(props.row,item.id)">{{item.authName}} </el-tag>
                  <i class="el-icon-caret-right"></i>
                </el-col>
                <el-col :span="19">
                  <el-row
                    :gutter="20"
                    :key="sub2.id"
                    v-for="(sub2,j) in item.children"
                    :class="[j != 0 ? 'topbd' : '']"
                    class="vmiddle"
                  >
                    <el-col :span="6" >
                      <el-tag closable type="success" @close="removeRights(props.row,sub2.id)">{{sub2.authName}} </el-tag>
                      <i class="el-icon-caret-right"></i>
                    </el-col>
                      <el-col :span="18">
                        <el-tag closable type="warning" :key="sub3.id" v-for="(sub3) in  sub2.children" @close="removeRights(props.row,sub3.id)">{{sub3.authName}} </el-tag>
                      </el-col>
                  </el-row>
                </el-col>
              </el-row>
            </template>
            </el-table-column>
            <el-table-column
            label="#"
            type="index"> </el-table-column>
            <el-table-column
            prop="roleName"
            label="角色名称"></el-table-column>
            <el-table-column
            prop="roleDesc"
            label="角色描述"></el-table-column>
            <el-table-column
            label="操作">
                <template  slot-scope="scope">
                    <el-button type="primary" icon="el-icon-edit" size="small" @click="btnEditClick(scope.row)">编辑</el-button>
                    <el-button type="danger" icon="el-icon-delete" size="small" @click="btnDeleteClick(scope.row)">删除</el-button>
                    <el-button type="success" icon="el-icon-setting" size="small" @click="btnSettingClick(scope.row)">设置权限</el-button>
                </template>
            </el-table-column>
        </el-table>
        </el-card>
        <!-- 新增用户 -->
        <el-dialog title="编辑角色" :visible.sync="dialogAddVisible" @close="addDialogClosed">
          <el-form :model="addForm" ref="addFormRef"  :rules="addFormRules">
            <el-form-item label="角色名称" :label-width="formLabelWidth"  prop="roleName" >
              <el-input v-model="addForm.roleName" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="角色描述" :label-width="formLabelWidth" prop="roleDesc">
              <el-input v-model="addForm.roleDesc" autocomplete="off"></el-input>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="dialogAddVisible = false">取 消</el-button>
            <el-button type="primary" @click="addRole(addForm)">确 定</el-button>
          </div>
        </el-dialog>
        <!-- 修改用户 -->
        <el-dialog title="编辑角色" :visible.sync="dialogEditVisible" @close="editDialogClosed">
          <el-form :model="editForm" ref="editFormRef"  :rules="editFormRules">
            <el-form-item label="角色名称" :label-width="formLabelWidth"  prop="roleName" >
              <el-input v-model="editForm.roleName" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="角色描述" :label-width="formLabelWidth" prop="roleDesc">
              <el-input v-model="editForm.roleDesc" autocomplete="off"></el-input>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="dialogEditVisible = false">取 消</el-button>
            <el-button type="primary" @click="editRole(editForm)">确 定</el-button>
          </div>
        </el-dialog>
        <!-- 设置角色权限 -->
        <el-dialog title="设置角色权限" :visible.sync="dialogChangeVisible"  @close='changeDialogClosed'>
          <el-tree
            :data="changeTree"
            :props="treeProps"
            show-checkbox
            ref="tree"
            default-expand-all
            node-key="id"
            >
          </el-tree>
          <div slot="footer" class="dialog-footer">
            <el-button @click="dialogChangeVisible = false">取 消</el-button>
            <el-button type="primary" @click="setRole()">确 定</el-button>
          </div>
        </el-dialog>
    </div>
</template>

<script>
export default {
  created() {
    this.getRoles()
  },
  data() {
    return {
      rolesData: [],
      editForm: {},
      addForm: {},
      changeTree: [],
      settingObj: {},
      formLabelWidth: '80px',
      dialogAddVisible: false,
      dialogEditVisible: false,
      dialogChangeVisible: false,
      treeProps: {
        label: 'authName',
        children: 'children',
        disabled: false,
        isLeaf: true
      },
      addFormRules: {
        roleName: [
          {
            required: true,
            message: '请输入角色名称',
            trigger: 'blur'
          },
          {
            min: 1,
            max: 10,
            message: '角色长度在1-10之间',
            trigger: 'blur'
          }
        ]
      },
      editFormRules: {
        roleName: [
          {
            required: true,
            message: '请输入角色名称',
            trigger: 'blur'
          },
          {
            min: 1,
            max: 10,
            message: '角色长度在1-10之间',
            trigger: 'blur'
          }
        ]
      }
    }
  },
  methods: {
    async getRoles() {
      const roleParams = {
        url: '/roles'
      }
      const res = await this.$send(roleParams)
      if (res.meta.status === 200) {
        this.rolesData = res.data
      }
    },
    editRole() {
      this.$refs.editFormRef.validate(async validate => {
        if (!validate) return
        const editParams = {
          url: `/roles/${this.editForm.id}`,
          method: 'PUT',
          params: {
            roleName: this.editForm.roleName,
            roleDesc: this.editForm.roleDesc
          }
        }
        const res = await this.$send(editParams)
        if (res.meta.status === 200) {
          this.$showMsg('修改成功')
          this.getRoles()
          this.dialogEditVisible = false
        }
      })
    },
    btnEditClick(role) {
      // json的转换会有一个深拷贝出来
      this.editForm = JSON.parse(JSON.stringify(role))
      this.dialogEditVisible = true
    },
    btnDeleteClick(role) {
      this.$confirm(`此操作将永久删除${role.roleName}, 是否继续?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.deleteRole(role)
      }).catch((err) => {
        console.log(err)
      })
    },
    async deleteRole(role) {
      const deleteParams = {
        url: `/roles/${role.id}`,
        method: 'DELETE',
        fullscreen: true
      }
      const res = await this.$send(deleteParams)
      if (res.meta.status === 200) {
        this.$showMsg(res.meta.msg)
        this.getRoles()
      }
    },
    async btnSettingClick(user) {
      this.dialogChangeVisible = true
      const setParams = {
        url: '/rights/tree',
        fullscreen: true
      }
      const res = await this.$send(setParams)
      if (res.meta.status === 200) {
        this.changeTree = res.data
        this.settingObj = user
        this.setCheckedKeys(user)
      }
    },
    // 编辑角色dialog关闭事件
    editDialogClosed () {
      this.$refs.editFormRef.resetFields()
    },
    addDialogClosed () {
      this.$refs.addFormRef.resetFields()
    },
    changeDialogClosed () {
      // this.$refs.changeFormRef.resetFields()
      this.$refs.tree.setCheckedKeys([])
      this.settingObj = {}
    },
    clickAddRole () {
      this.dialogAddVisible = true
    },
    addRole (role) {
      this.$refs.addFormRef.validate(async validate => {
        if (!validate) return
        const addParams = {
          url: '/roles',
          method: 'POST',
          params: {
            roleName: role.roleName,
            roleDesc: role.roleDesc
          }
        }
        const res = await this.$send(addParams)
        if (res.meta.status === 200) {
          this.$showMsg('新增角色成功')
          this.getRoles()
          this.dialogAddVisible = false
        }
      })
    },
    async setCheckedKeys(role) {
      const keyParams = {
        url: `/roles/${role.id}`,
        fullscreen: true
      }
      const res = await this.$send(keyParams)
      if (res.meta.status === 200) {
        console.log(res.data.rids)
        const keys = res.data.rids.split(',')
        this.$refs.tree.setCheckedKeys(keys)
      }
    },
    async setRole() {
      console.log(this.$refs.tree.getCheckedNodes())
      console.log(this.$refs.tree.getCheckedKeys())
      const roleParams = {
        url: `/roles/${this.settingObj.id}/rights`,
        method: 'POST',
        params: {
          rids: this.$refs.tree.getCheckedKeys()
        },
        fullscreen: true
      }
      const res = await this.$send(roleParams)
      if (res.meta.status === 200) {
        this.$showMsg('设置权限成功')
        this.dialogChangeVisible = false
      }
    },
    async removeRights(sub0, id) {
      const rParams = {
        url: `roles/${sub0.id}/rights/${id}`,
        method: 'DELETE',
        fullscreen: true
      }
      const res = await this.$send(rParams)
      if (res.meta.status === 200) {
        this.$showMsg('删除权限成功')
        this.handleRemove(sub0, id)
      }
    },
    handleRemove(sub0, id) {
      console.log(111)
      if (sub0.children != null && sub0.children.length > 0) {
        sub0.children.forEach((item, index) => {
          if (item.id === id) {
            console.log(item, index)
            sub0.children.splice(index, 1)
          } else {
            this.handleRemove(item, id)
          }
        })
      }
    }
  }
}
</script>

<style lang="less" scoped>
.el-bread-group{
    height: 40px;
    line-height: 40px;
    background-color: #E9EEF3;
    padding-left: 10px;
}
.card{
    margin-left: 10px;
    margin-right: 10px;
    box-shadow: 0,0,1px;
}
.btn-add{
    display: flex;
    justify-content: flex-start;
    margin-bottom: 10px;
    margin-right: 10px;
}
.topbd{
  border-top: 1px solid #eee;
}
.botbd{
  border-bottom: 1px solid #eee;
}
.vmiddle{
  display: flex;
  align-items: center;
}
.el-col{
  margin-top: 4px;
  margin-bottom: 4px;
}
.el-tag{
  margin-right: 10px;
  margin-bottom: 4px;
  margin-top: 4px;
}
</style>
